package ca.intelliware.commons.virtualization.vmware;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import ca.intelliware.commons.virtualization.CenterServer;
import ca.intelliware.commons.virtualization.DataCenter;
import ca.intelliware.commons.virtualization.VMachine;

import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.ManagedObject;
import com.vmware.vim25.mo.ServiceInstance;

public class VmCenterServer implements CenterServer {
	private ServiceInstance serviceInstance;

	
	VmCenterServer(ServiceInstance serviceInstance) {
		this.serviceInstance = serviceInstance;
	}

	public URL getUrl() {
		return this.serviceInstance.getServerConnection().getUrl();
	}

	public DataCenter dataCenter(String id) throws Exception {
		DataCenter foundDataCenter = null;
		for (DataCenter dataCenter : dataCenters()) {
			if (dataCenter.getId().equalsIgnoreCase(id)) {
				foundDataCenter = dataCenter;
				break;
			}
		}
		return foundDataCenter;
	}

	public List<DataCenter> dataCenters() throws Exception {
		ArrayList<ManagedObject> datacenterManagedObjects = VmwareVmExplorer
				.findManagedObjectsByType(serviceInstance.getRootFolder()
						.getChildEntity(), "Datacenter");
		List<DataCenter> dataCenters = new ArrayList<DataCenter>();
		for (ManagedObject datacenterManagedObject : datacenterManagedObjects) {
			dataCenters.add(new VmDataCenter(
					(Datacenter) datacenterManagedObject));
		}
		return dataCenters;	
	}

	public String inventoryReport() throws Exception {
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(this.getUrl().toExternalForm()).append("\n");
		for (DataCenter dataCenter : dataCenters()) {
			strBuilder.append(dataCenter.inventoryReport());
		}
		strBuilder.append("\n");
		return strBuilder.toString();
	}

	public void revertAllVirtualMachinesToLastSnapshot() throws Exception {
		for (DataCenter dataCenter : dataCenters()) {
			dataCenter.revertAllVirtualMachinesToLastSnapshot();
		}

	}

	public List<VMachine> virtualMachine(String id) throws Exception {
		List<VMachine> virtualMachines = new ArrayList<VMachine>();
		for (DataCenter dataCenter : dataCenters()) {
			virtualMachines.addAll(dataCenter.virtualMachine(id));
		}
		return virtualMachines;
	}
}
